package com.sun.controller;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.PushGateway;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 模拟推送数据到PushGateway
 */
public class MockPushGateway {

    private static final String PUSH_GATEWAY_RUL = "localhost:9091";

    public static void main(String[] args) throws IOException {
//        method1();
        method2();
    }

    private static void method1() throws IOException {
        // 任务名称
        String job = "sun-job1";
        // 指标名称 支持_和:
//        String metric = "test_cpu_metric";
        String metric = "test_metric_1";
        // 描述
        String help = "CPU Metric Help";
        // 标签
        String[] labelNames = new String[]{ "CPU", "GPU", "TIME" };
        // 标签值
        String[] labelValues = new String[]{ "111", "222", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date())};

        CollectorRegistry registry = new CollectorRegistry();
        // Gauge：可增可减的仪表盘
        Gauge gauge = Gauge.build()
                .name(metric)
                .help(help)
                .labelNames(labelNames)
                .create();
        gauge.labels(labelValues).set(new BigDecimal("1.02").doubleValue());
        registry.register(gauge);

        PushGateway pushGateway = new PushGateway(PUSH_GATEWAY_RUL);
        pushGateway.pushAdd(registry, job);
        System.out.println("推送完成！");
    }

    private static void method2() throws IOException {
        CollectorRegistry registry = new CollectorRegistry();
        Gauge gauge = Gauge.build("test_memory_metric", "Memory Metric Help")
                .labelNames("Memory", "Disk")
                .create();
        gauge.labels("8GB", "1T").set(new BigDecimal("1.2").doubleValue());
        gauge.register(registry);

        Map<String, String> groupingKey = new HashMap<>();
        groupingKey.put("instance", "10.137.0.1");
        groupingKey.put("cluster_name", "SH");
        groupingKey.put("nc_model", "PV52P1B1(96C/775G)");
        groupingKey.put("nc_num", "3");

        PushGateway pg = new PushGateway(PUSH_GATEWAY_RUL);
        pg.pushAdd(registry, "sun-job2", groupingKey);
    }

}
